package edu.polsl.bio.str.manager.error;

import edu.polsl.bio.str.common.messaging.StrDotsPayload;
import edu.polsl.bio.str.common.util.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * //todo class description
 * <p/>
 * Created on: Jul 15, 2011 12:11:38 PM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class BulkInsertErrorHandlerImpl implements BulkInsertErrorHandler {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(BulkInsertErrorHandlerImpl.class.getName());

  private String dumpDir;

  private String dumpFilePrefix;

  @Override
  public void handleError(StrDotsPayload payload, Exception ex) {
    log.debug("Handling bulk insert error for {}", payload.getJobId());
    FileOutputStream outputStream = null;
    try {
      File outFile = File.createTempFile(dumpFilePrefix + "_" + payload.getJobId() + "_", ".bin", new File(dumpDir));
      log.info("Storing dots for job id={} into {} file", payload.getJobId(), outFile.getAbsolutePath());
      outputStream = new FileOutputStream(outFile);
      outputStream.write(SerializationUtils.writeObject(payload));
    } catch (Exception e) {
      log.error("Exception occurred during serialization of dot plots", e);
    } finally {
      if (outputStream != null) {
        try {
          outputStream.close();
        } catch (IOException e) {
          log.error("Exception occurred during closing stream", e);
        }
      }
    }
  }

  public void setDumpDir(String dumpDir) {
    this.dumpDir = dumpDir;
  }

  public void setDumpFilePrefix(String dumpFilePrefix) {
    this.dumpFilePrefix = dumpFilePrefix;
  }
}
